
function AllReady() {
  var mstform = Ext.getCmp("PoUrgeM"); //获取容器
  var PhidPc = mstform.queryById("PhidPc");
  var PhidCnt = mstform.queryById("PhidContract");
  var dgrid = Ext.getCmp("PoUrgeD");
  var Toolbar = Ext.getCmp("toolbar");
  var dstore = dgrid.store;
  var user_pro_type = mstform.queryById("user_pro_type");
  var user_ywlx = mstform.queryById("user_ywlx");
  var user_xmywlx = mstform.queryById("user_xmywlx"); // 新增字段
  var PhidBuyer = mstform.queryById("PhidBuyer");
  var user_regional_center = mstform.queryById("user_regional_center");
  var user_ejbm = mstform.queryById("user_ejbm");
  var user_division = mstform.queryById("user_division"); //获取字段
  var user_product_line = mstform.queryById("user_product_line");
  var TotalMony = mstform.queryById("TotalMony");
  var TotalTaxMony = mstform.queryById("TotalTaxMony");
  var user_tax_amt = mstform.queryById("user_tax_amt");
  var PhidBuyer = mstform.queryById("PhidBuyer");
  var BuyerPhone = mstform.queryById("BuyerPhone");
  var PhidOrderDept = mstform.queryById("PhidOrderDept");
  var user_gys = mstform.queryById("user_gys");
  var user_cnt_no = mstform.queryById("user_cnt_no");
  var ContractName = mstform.queryById("ContractName");
  var PhidVendor = mstform.queryById("PhidVendor");
   var user_cgzz = mstform.queryById("user_cgzz");  // 采购组织字段

  // 新增：获取项目业务类型信息并设置显示名称
  function getPtInfo2(phid) {
    if (!phid) return;
    execServer("getPtInfo2", { phid: phid }, function (res) {
      if (res.count == 0) return;
      const datas = JSON.parse(res.data)[0].extendObjects;
      console.log(datas, "getPtInfo2 项目业务类型信息");
      
      // 设置 user_xmywlx 字段值，同时设置编码和名称
      if (datas.user_ywlx && datas.c_name) {
        user_xmywlx.setValue(datas.user_ywlx);
        user_xmywlx.setRawValue(datas.c_name);
        console.log("设置 user_xmywlx:", datas.user_ywlx, datas.c_name);
      }
    });
  }

  user_cnt_no.on("beforetriggerclick", function (eOp, ignoreBeforeEvent) {
    var pc = mstform.getItem("PhidPc").getValue();
    if (Ext.isEmpty(pc)) {
      Ext.Msg.alert("提示", "请先选择项目！");
      mstform.getItem("PhidPc").focus();
      return false;
    } else {
      mstform.getItem("user_cnt_no").setOutFilter({
        phid_pc: pc, //phid_pc 字段是通用帮助中的字段
      });
    }
  });
  
  user_cnt_no.addListener("helpselected", function (data) {
    //表头帮助窗口选择后触发
    console.log(data);
    PhidCnt.setValue(data.data.phid);
    ContractName.setValue(data.data.bill_name);
    PhidVendor.setValue(data.data.phid_supply_ent);
    BatchBindCombox([PhidVendor]);
    BatchBindCombox([PhidCnt]);
    
     
      // 获取合同的采购组织信息
      execServer("getCntMInfoByPhid", { phid: data.data.phid }, function (res) {
        try {
          if (res.count > 0) {
            const cntData = JSON.parse(res.data)[0].extendObjects;
            console.log("合同详情信息：", cntData);
            
            // 设置采购组织
            if (cntData.payid) {
              user_cgzz.setValue(cntData.payid);
              BatchBindCombox([user_cgzz]);
              console.log("设置采购组织：", cntData.payid);
            }
          }
        } catch (error) {
          console.error("获取合同采购组织失败：", error);
        }
      });
  });
  
  //user_cnt_no.addListener("getCntMInfoByPhid", function (data) {
    //表头帮助窗口选择后触发
    //console.log(data);
    //user_cgzz.setValue(data.payid);
    //BatchBindCombox([user_cgzz]);
  //});
  
  PhidCnt.addListener("change", function () {
    getCntPayDetailInfo();
    execServer("getCntInfo", { cnt: PhidCnt.getValue() }, function (res) {
      const datasGetCntInfo = JSON.parse(res.data)[0].extendObjects;

      if (datasGetCntInfo) {
        if (datasGetCntInfo.pc) {
          console.log(datasGetCntInfo.pc, "PhidPc.setValue(datasGetCntInfo?.pc");
          PhidPc.setValue(datasGetCntInfo?.pc);
          BatchBindCombox([PhidPc]);
        }
        if (datasGetCntInfo.upt) {
          user_pro_type.setValue(datasGetCntInfo.upt);
        }
        if (datasGetCntInfo.ubt) {
          user_ywlx.setValue(datasGetCntInfo.ubt);
          BatchBindCombox([user_ywlx]);
        }
        if (datasGetCntInfo.up) {
          PhidBuyer.setValue(datasGetCntInfo.up);
          BatchBindCombox([PhidBuyer]);
        }
      }
    });
  });
  
  PhidBuyer.addListener("change", function (args) {
    execServer("getModileYHD", { phidPhonea: args.value }, function (res) {
      try {
        var obj = JSON.parse(res.data);
        BuyerPhone.setValue(obj[0].extendObjects.mobile1);
      } catch (error) {}
    });
  });
  
  PhidPc.addListener("change", function (args) {
    if (PhidPc.getValue()) {
      getSyQty(mstform.queryById("PhidPc").getValue());

      // 获取项目基本信息
      execServer("getPtInfoByPhid", { phid: PhidPc.getValue() }, function (res) {
        const datas = JSON.parse(res.data)[0].extendObjects;
        user_division.setValue(datas.division_phid);
        user_product_line.setValue(datas.midwife_phid);
        user_regional_center.setValue(datas.regional_center_phid);
        user_ejbm.setValue(datas.org_phid);
        BatchBindCombox([user_ejbm]);
        BatchBindCombox([user_division]);
        BatchBindCombox([user_product_line]);
        BatchBindCombox([user_regional_center]);
      });

      // 新增：获取项目业务类型信息
      getPtInfo2(PhidPc.getValue());

      if (!PhidCnt.getValue()) return;
      execServer("getCntMInfoByPhid", { phid: PhidCnt.getValue() }, function (res) {
        try {
          const datasGetCntMInfoByPhid = JSON.parse(res.data)[0].extendObjects;
          PhidOrderDept.setValue(datasGetCntMInfoByPhid.dept_phid);
          BatchBindCombox([PhidOrderDept]);
          user_gys.setValue(datasGetCntMInfoByPhid.supply_id);
          BatchBindCombox([user_gys]);
        } catch (error) {}
      });
    } else {
      // 项目清空时，清空 user_xmywlx 字段
      user_xmywlx.setValue('');
      user_xmywlx.setRawValue('');
    }
  });

  TotalMony.addListener("change", function () {
    user_tax_amt.setValue(TotalTaxMony.getValue() - TotalMony.getValue());
  });
  
  TotalTaxMony.addListener("change", function () {
    user_tax_amt.setValue(TotalTaxMony.getValue() - TotalMony.getValue());
  });

  // 用于状态是否发生变化
  let current = otype;
  dstore.on("datachanged", async function (dstore, eOpts) {
    const records = dstore.getRange();

    mstform.on("dataready", async () => {
      console.log(`PhId`, mstform.queryById("PhId").getValue());
      if (current != otype) {
        current = otype;
        await getSyQty(mstform.queryById("PhidPc").getValue());
      }
      setDgridValue(dstore);
    });

    if (otype == "add") {
      const records = dstore.getRange();
      console.log(dgrid.getStore().getRange()[0].data);
      if (!dgrid.getStore().getRange()[0].data.user_shsjljsl) {
        for (const record of records) {
          record.set("user_shsjljsl", window.qtytotal[record.get("PhidItemData")]);
          record.set("ConfirmQty", record.get("Qty"));
        }
      }
      changeQty();
    }
    if (otype != "add") return;
    setDgridValue(dstore);
  });

  function setDgridValue(dstore) {
    if (otype == "add" || otype == "edit") {
      const records = dstore.getRange();
      for (const record of records) {
        record.set("user_shsjljsl", window.qtytotal[record.get("PhidItemData")]);
        try {
          execServer(
            "GETitemzq",
            {
              phid: record.data.PhidItemData,
            },
            function (res) {
              try {
                const obj = JSON.parse(res.data)[0].extendObjects;
                if (!obj.pur_lead) return;
                record.set("user_ckarrival_dt", addDaysToDate(new Date(), obj.pur_lead));
                if (otype != "add") record.commit();
              } catch (error) {}
            }
          );
        } catch (error) {}
      }
      dgrid.getView().refresh();
    }
  }

  function changeQty(params) {
    dstore.each(function (item) {
      let amt_1 = Ext.Number.from(item.get("user_yhsyl"), 0);
      let amt_2 = Ext.Number.from(item.get("user_shsjljsl"), 0);
      if (amt_1 > amt_2) {
        item.set("Qty", amt_2);
      } else {
        item.set("Qty", amt_1);
      }
      dgrid.getView().refresh();
    });
  }
  
  //监听表体编辑
  dgrid.addListener("edit", (dt, e) => {
    const dstore = e.record;
    console.log("监听读取", dstore);
    edit(dstore);
  });

  dgrid.getStore().addListener("datachanged", () => {
    return
    if (otype == "view") return;
    mstform.queryById("user_yfkje").setValue((window._catch_cnt_pay?.bal_percent || 0) * (Number(mstform.queryById("TotalTaxMony").getValue()) || 0));
    mstform.queryById("user_yfksyje").setValue((window._catch_cnt_pay?.bal_percent || 0) * (Number(mstform.queryById("TotalTaxMony").getValue()) || 0));
  });

  //编辑逻辑 - 增加 user_xmywlx 校验逻辑
  function edit(dstore) {
    if (!dstore.get("PhidItemid")) return;
    const phidItem = dstore.get("PhidItemData");
    const Qty = dstore.get("Qty");
    const user_yhsyl = dstore.get("user_yhsyl");
    const user_shsjljsl = dstore.get("user_shsjljsl");
    const phid_pc = mstform.queryById("PhidPc").getValue();
    const user_yqarrival_dt = dstore.get("user_yqarrival_dt");
    const user_ckarrival_dt = dstore.get("user_ckarrival_dt");
    
    // 获取项目业务类型
    const xmywlxValue = user_xmywlx.getValue();
    console.log("当前项目业务类型:", xmywlxValue);
    
    console.log(new Date(user_yqarrival_dt) < new Date(user_ckarrival_dt), "到货时间判断");
    if (user_yqarrival_dt && user_ckarrival_dt && new Date(user_yqarrival_dt) < new Date(user_ckarrival_dt)) {
      dstore.set("user_yqarrival_dt", undefined);
      Ext.Msg.alert("提示", "要求到货日期不能早于参考到货日期！");
    }
    
    console.log(`缓冲`, window.qtytotal, phidItem, phid_pc);
    
    // 新增：根据 user_xmywlx 值决定是否校验 user_shsjljsl 字段
    if (xmywlxValue == "8570000000000353") {
      // 当 user_xmywlx 等于 8570000000000353 时，不校验 user_shsjljsl 字段
      console.log("项目业务类型为 8570000000000353，跳过深化设计剩余量校验");
      
      // 只校验合同采购剩余量
      if (Qty > user_yhsyl) {
        Ext.Msg.alert("提示", "要货数量超出合同采购剩余量");
        dstore.set("Qty", 0);
      }
    } else {
      // 当 user_xmywlx 等于其他值或为空时，正常校验所有字段
      console.log("项目业务类型不为 8570000000000353，进行完整校验");
      
      if (Qty > user_yhsyl || Qty > user_shsjljsl) {
        Ext.Msg.alert("提示", "要货数量超出合同采购剩余量或深化设计剩余量");
        dstore.set("Qty", 0);
      }
      
      if ((Number(window.qtytotal[phidItem]) || 0) < Qty) {
        Ext.Msg.alert("提示", "要货数量超出！当前剩余：" + dstore.get("user_shsjljsl"));
        dstore.set("Qty", 0);
        dstore.set("ConfirmQty", 0);
      }
    }
    
    mstform.queryById("user_yfkje").setValue((window._catch_cnt_pay?.bal_percent || 0) * (Number(mstform.queryById("TotalTaxMony").getValue()) || 0));
    mstform.queryById("user_yfksyje").setValue((window._catch_cnt_pay?.bal_percent || 0) * (Number(mstform.queryById("TotalTaxMony").getValue()) || 0));
    dgrid.getView().refresh();
  }
  
  //查找当前物料可用数量
  getSyQty(mstform.queryById("PhidPc").getValue());
  async function getSyQty(phid_pc) {
    console.log(phid_pc, "项目状态");
    if (!phid_pc) return;
    await execServer("getYhdQtyByPhidPcAndItem", { phid_pc }, async (res) => {
      console.log(`累计数量`, res);
      if (res.count == 0) {
        window.qtytotal = {};
        return;
      } else {
        let total = JSON.parse(res.data).reduce((value, item) => {
          value[item.extendObjects.phiditem] = item.extendObjects.qty;
          return value;
        }, {});
        console.log(`mstform.getItem("PhId").getValue()`, mstform.getItem("PhId").getValue());
        const phid = mstform.getItem("PhId").getValue() ? mstform.getItem("PhId").getValue() : "10086";
        await execServer("getYhdPhidItemTotalQty", { phid_pc, phid }, (res) => {
          console.log(`累计用过数量`, res);
          let ysy = {};
          if (res.count == 0) {
          } else {
            const _data = JSON.parse(res.data);
            ysy = _data.reduce((value, item) => {
              value[item.extendObjects.phiditem] = item.extendObjects.qty;
              return value;
            }, {});
          }
          window.qtytotal = {};
          for (let key in total) {
            window.qtytotal[key] = (Number(total[key]) || 0) - (Number(ysy[key]) || 0);
          }
          console.log(`qtytotal`, window.qtytotal);
        });
      }
    });
  }

  // 获取合同条款
  otype == "view" && getCntPayDetailInfo();
  function getCntPayDetailInfo() {
    const cnt = mstform.queryById("PhidContract").getValue();
    if (!cnt) return;
    execServer("getCntPayDetailInfo", { cnt }, (res) => {
      if (res.count == 0) return;
      const _data = JSON.parse(res.data).filter((item) => {
        if ((Number(item.extendObjects.namephid) || 0) == 8570000000000001) {
          return item;
        }
      });

      if (_data.length != 0) {
        window._catch_cnt_pay = _data[0].extendObjects;
        mstform.queryById("user_yfkhebl").setValue(_data[0].extendObjects?.bal_percent || 0);
        mstform.queryById("user_yfkje").setValue((_data[0].extendObjects?.bal_percent || 0) * (Number(mstform.queryById("TotalTaxMony").getValue()) || 0));
        mstform.queryById("user_yfksyje").setValue((_data[0].extendObjects?.bal_percent || 0) * (Number(mstform.queryById("TotalTaxMony").getValue()) || 0));
      }
    });
  }

  // 新增：页面加载时初始化 user_xmywlx 字段
  if (otype == "add" || otype == "edit") {
    var pc = mstform.getItem("PhidPc").getValue();
    if (pc) {
      getPtInfo2(pc);
    }
  }
  
} //End -- AllReady

function addDaysToDate(date, days) {
  let targetDate = date instanceof Date ? date : new Date(date);
  targetDate.setTime(targetDate.getTime() + days * 24 * 60 * 60 * 1000);
  return targetDate;
}